package com.opticon.vaadinR.ui.panel;

import com.google.common.io.Files;
import com.opticon.vaadinR.interfaces.DashboardTab;
import com.vaadin.Application;
import com.vaadin.terminal.StreamResource;
import com.vaadin.ui.Component;
import com.vaadin.ui.Embedded;
import com.vaadin.ui.Panel;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * This class is a
 */
public class SimplePNGTab extends Panel implements DashboardTab {
    private static Logger logger = Logger.getLogger(SimplePNGTab.class);

    private String iTitle = "GraphExample";
    private Panel iInnerPanel = new Panel();
    private File iFile;
    private final Application iApplication;

    public SimplePNGTab(File aFile, Application aApplication) {
        super();
        iFile = aFile;
        iApplication = aApplication;
        initialize();
    }


    public Component getComponent() {
        return this;
    }

    public void initialize() {
        this.setScrollable(true);
        this.setSizeFull();

        setCaption();
        this.addComponent(iInnerPanel);


        final InputStream is;
        try {
            // Set caption without file extension.
            setCaption(iFile.getName().split("\\.")[0]);

            is = Files.newInputStreamSupplier(iFile).getInput();
            StreamResource.StreamSource lStreamSource = new StreamResource.StreamSource() {
                public InputStream getStream() {
                    return is;
                }
            };

            StreamResource lStreamResource = new StreamResource(lStreamSource, iFile.getName(), iApplication);

            Embedded iImage = new Embedded();
            iImage.setSource(lStreamResource);

            iInnerPanel.removeAllComponents();
            iInnerPanel.addComponent(iImage);

            iInnerPanel.requestRepaintAll();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }


    /**
     * Sets the field's caption <code>String</code>. Caption is the visible
     * name of the field. This method will trigger a
     * {@link com.vaadin.terminal.Paintable.RepaintRequestEvent
     * RepaintRequestEvent}.
     */
    public void setCaption() {
        super.setCaption(iTitle);
    }
}
